<script setup>
import { ref, watch, onBeforeMount } from 'vue'
import { User, Lock, InfoFilled } from '@element-plus/icons-vue'
import {
  employeeLoginService,
  employeeCheckCodeService
} from '@/api/employee.js'
import { useRouter } from 'vue-router'
import { useEmployeeStore } from '@/stores'
import { ElMessage } from 'element-plus'

const isRegister = ref(false)

const formModel = ref({
  username: '',
  password: '',
  repassword: '',
  checkCode: '',
  checkCodeId: ''
})

// 获取表单对象
const form = ref()

// 是否记住我
const rememberMe = ref(false)

onBeforeMount(() => {
  // 从cookie获取用户名和密码
  if (document.cookie.length > 0) {
    let employeeMe

    const cookieString = decodeURIComponent(document.cookie)
    const cookies = cookieString.split(';')
    for (let i = 0; i < cookies.length; i++) {
      let cookie = cookies[i].trim()
      if (cookie.startsWith('employeeMe=')) {
        employeeMe = JSON.parse(
          cookie.slice('employeeMe='.length, cookie.length)
        )
        break
      }
    }

    if (employeeMe) {
      formModel.value.username = employeeMe.username
      let password = employeeMe.password
      if (password) {
        formModel.value.password = password
        rememberMe.value = true
      }
    }
  }
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }, //非空校验，失焦时校验
    { len: 10, message: '用户名必须是10位的字符', trigger: 'blur' } // 默认change输入时校验
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位的非空字符',
      trigger: 'blur'
    }
  ],
  repassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15的非空字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        // rule是校验规则，value是当前要校验的字段值，callback是回调函数（无论成功还是失败，都需要callback回调）
        // 判断value和当前form中收集的password是否一致
        if (value !== formModel.value.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  checkCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    {
      pattern: /^\S{4}$/,
      message: '验证码是4位的非空字符',
      trigger: 'blur'
    }
  ]
}

const checkCode = ref()

// 获取验证码
const getCheckCode = async (checkCodeId) => {
  await employeeCheckCodeService(checkCodeId).then((response) => {
    checkCode.value = 'data:image/jpg;base64,' + response.data.checkCode
    formModel.value.checkCodeId = response.data.checkCodeId
  })
}
getCheckCode()

// 节流处理：在规定时间内，只能触发一次
const throttle = (func, limit) => {
  let inThrottle = false
  return function () {
    const args = arguments
    console.log(args)
    const context = this
    if (!inThrottle) {
      func.apply(context, args)
      inThrottle = true
      setTimeout(() => (inThrottle = false), limit)
    }
  }
}

const getCheckCodeThrottled = throttle(getCheckCode, 1000) // 1000ms为节流时间间隔

//切换的时候，重置表单内容
watch(isRegister, () => {
  const checkCodeId = formModel.value.checkCodeId
  formModel.value = {
    username: '',
    password: '',
    repassword: '',
    checkCode: '',
    checkCodeId: ''
  }
  formModel.value.checkCodeId = checkCodeId
})

const router = useRouter()

const employeeStore = useEmployeeStore()

const login = async () => {
  // 表单校验
  await form.value.validate()
  try {
    // 校验通过，可以发送登录请求
    await employeeLoginService({ ...formModel.value }).then((response) => {
      employeeStore.setEmployeeInfo(response.data)
      ElMessage.success(response.message)

      // 登录成功，判断是否记住我
      const date = new Date()
      date.setTime(date.getTime() + 7 * 24 * 60 * 60 * 1000)
      if (rememberMe.value) {
        // 存储到cookie，过期时间为7天后
        document.cookie =
          'employeeMe=' +
          JSON.stringify({
            username: formModel.value.username,
            password: formModel.value.password
          }) +
          ';expires=' +
          date.toUTCString() +
          ';path=/'
      } else {
        // 未设置记住我，只保存账号
        document.cookie =
          'employeeMe=' +
          JSON.stringify({
            username: formModel.value.username
          }) +
          ';expires=' +
          date.toUTCString() +
          ';path=/'
        // 'employeeMe=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/'
      }

      router.push('/')
    })
  } catch (error) {
    // 处理Promise被拒绝
    getCheckCode()
  }
}

const register = async () => {
  // 表单校验
  await form.value.validate()
}
</script>

<template>
  <!-- 一行有24份 -->
  <el-row class="login-page">
    <!-- 一列 -->
    <el-col :span="12" class="bg">
      <h1 class="title">智慧停车场管理系统</h1>
    </el-col>

    <!-- 占6份，左边margin3份 -->
    <el-col :span="12">
      <el-container class="form">
        <el-main>
          <el-form
            :model="formModel"
            :rules="rules"
            ref="form"
            size="large"
            label-width="auto"
            autocomplete="off"
            :hide-required-asterisk="true"
            v-if="isRegister"
            @keydown.enter="register"
          >
            <!-- 表单的一行 -->
            <el-form-item>
              <!-- 表单元素 -->
              <h1 style="font-size: 30px">注册</h1>
            </el-form-item>

            <el-form-item prop="username" label="用户名">
              <el-input
                :prefix-icon="User"
                placeholder="请输入用户名"
                v-model="formModel.username"
              >
              </el-input>
            </el-form-item>

            <el-form-item prop="password" label="密码">
              <el-input
                :prefix-icon="Lock"
                type="password"
                placeholder="请输入密码"
                v-model="formModel.password"
              >
              </el-input>
            </el-form-item>

            <el-form-item prop="repassword" label="确认密码">
              <el-input
                :prefix-icon="Lock"
                type="password"
                placeholder="请输入再次密码"
                v-model="formModel.repassword"
              >
              </el-input>
            </el-form-item>

            <el-form-item prop="checkCode" label="验证码">
              <el-input
                :prefix-icon="InfoFilled"
                type="text"
                placeholder="请输入验证码"
                v-model="formModel.checkCode"
              >
              </el-input>
            </el-form-item>

            <el-form-item>
              <div class="check-code">
                <img :src="checkCode" alt="check code" />
                <el-link
                  type="primary"
                  :underline="false"
                  @click="getCheckCodeThrottled(formModel.checkCodeId)"
                >
                  看不清，换一张
                </el-link>
              </div>
            </el-form-item>

            <el-form-item>
              <el-button
                class="button"
                type="primary"
                auto-insert-space
                @click="register"
              >
                注册
              </el-button>
            </el-form-item>

            <el-form-item class="flex">
              <el-link
                type="default"
                :underline="false"
                @click="isRegister = false"
              >
                ← 返回
              </el-link>
            </el-form-item>
          </el-form>

          <el-form
            label-width="auto"
            :model="formModel"
            :rules="rules"
            ref="form"
            size="large"
            autocomplete="off"
            :hide-required-asterisk="true"
            v-else
            @keydown.enter="login"
          >
            <el-form-item>
              <h1 style="font-size: 30px">登录</h1>
            </el-form-item>

            <el-form-item prop="username" label="用户名">
              <el-input
                :prefix-icon="User"
                placeholder="请输入用户名"
                v-model="formModel.username"
              ></el-input>
            </el-form-item>

            <el-form-item prop="password" label="密码">
              <el-input
                :prefix-icon="Lock"
                type="password"
                placeholder="请输入密码"
                v-model="formModel.password"
              ></el-input>
            </el-form-item>

            <el-form-item prop="checkCode" label="验证码">
              <el-input
                :prefix-icon="InfoFilled"
                type="text"
                placeholder="请输入验证码"
                v-model="formModel.checkCode"
              ></el-input>
            </el-form-item>

            <el-form-item>
              <div class="check-code">
                <img :src="checkCode" alt="check code" />
                <el-link
                  type="primary"
                  :underline="false"
                  @click="getCheckCodeThrottled(formModel.checkCodeId)"
                >
                  看不清，换一张
                </el-link>
              </div>
            </el-form-item>

            <el-form-item class="flex">
              <div class="flex">
                <el-checkbox v-model="rememberMe">记住我</el-checkbox>
                <el-link type="primary" :underline="false">忘记密码？</el-link>
              </div>
            </el-form-item>

            <el-form-item>
              <el-button
                class="button"
                type="primary"
                auto-insert-space
                @click="login"
                >登录</el-button
              >
            </el-form-item>

            <el-form-item class="flex">
              <el-link
                type="primary"
                :underline="false"
                @click="
                  ElMessage({
                    showClose: true,
                    type: 'warning',
                    message: '注册功能暂未开放',
                    grouping: true
                  })
                "
              >
                注册 →
              </el-link>
            </el-form-item>
          </el-form>
        </el-main>

        <el-footer> 小提示 ©2024 Created by lt </el-footer>
      </el-container>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-page {
  width: 100%;
  height: 100vh;
  background-color: #fff;

  .bg {
    background:
      url('@/assets/login-car.png') no-repeat center 70% / 200px auto,
      url('@/assets/login-bg.jpg') no-repeat center / cover;
    border-radius: 0 20px 20px 0;

    .title {
      font-size: 70px;
      color: #fff;
      text-align: center;
      margin-top: 300px;
    }
  }

  .el-col {
    height: 100%;
  }

  .form {
    align-items: center;
    height: 100%;
    width: 100%;

    .el-main {
      height: 95%;
      width: 60%;
      display: flex;
      justify-content: center;
      align-items: center;

      .el-form {
        width: 100%;
        margin: 0 30px;
      }

      .button {
        margin: auto;
        width: 80%;
      }

      .flex {
        width: 100%;
        display: flex;
        justify-content: space-around;
      }

      .check-code {
        width: 100%;
        display: flex;
        justify-content: end;

        img {
          width: 100px;
          height: 40px;
          margin-right: 5px;
        }
      }
    }

    .el-footer {
      width: 100%;
      height: 40px;
      background-color: #f2f3f5;
      font-size: 10px;
      text-align: center;
      line-height: 40px;
    }
  }
}
</style>
